/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pos.system.standard.ui;

import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException;
import java.awt.Component;
import java.awt.Container;
import java.awt.Event;
import java.awt.FocusTraversalPolicy;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import pos.system.Constants;
import pos.system.PropertyBag;
import pos.system.Role;
import pos.system.database.DBConstant;
import pos.system.database.MySqlConnector;
import pos.system.standard.ui.util.GuiUtil;

/**
 *
 * @author Shameera
 */
public class LoginWindow extends javax.swing.JFrame {

//    PropertyBag pBag;
    private MySqlConnector dbConnector;
    private Role role;

    /**
     * Creates new form LoginWindow
     */
    private LoginWindow() {
        initComponents();
//        GuiUtil.initMainPanel(login_panel);
        this.setLocationRelativeTo(this);
        
    }

//    public LoginWindow(PropertyBag pBag) {
//        this();
//        loginwindow_usernameField.setText("sham");
//        loginwindow_passwordField.setText("sham");
//        this.pBag = pBag;
//        
//    }
    public LoginWindow(Role r) {
        this();
        this.role = r;
//        loginwindow_usernameField.setText("sham");
//        loginwindow_passwordField.setText("sham");
        String login = "login";
        loginwindow_loginButton.getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW)
                .put(KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK), login);
        loginwindow_loginButton.getActionMap().put(login, new LoginKeyAction());
    }

    private class LoginKeyAction extends AbstractAction{

        @Override
        public void actionPerformed(ActionEvent e) {
            loginwindow_loginButtonActionPerformed(e);
        }
        
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        login_panel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        loginwindow_usernameField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        loginwindow_passwordField = new javax.swing.JPasswordField();
        loginwindow_loginButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setFocusTraversalPolicy(setFocusTraversalPolicy());
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        login_panel.setBackground(new java.awt.Color(187, 187, 105));
        login_panel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Username :");

        loginwindow_usernameField.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Password :");

        loginwindow_passwordField.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        loginwindow_loginButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/login.png"))); // NOI18N
        loginwindow_loginButton.setMnemonic('L');
        loginwindow_loginButton.setText("Login");
        loginwindow_loginButton.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        loginwindow_loginButton.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        loginwindow_loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginwindow_loginButtonActionPerformed(evt);
            }
        });
        loginwindow_loginButton.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                loginwindow_loginButtonFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                loginwindow_loginButtonFocusLost(evt);
            }
        });

        javax.swing.GroupLayout login_panelLayout = new javax.swing.GroupLayout(login_panel);
        login_panel.setLayout(login_panelLayout);
        login_panelLayout.setHorizontalGroup(
            login_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(login_panelLayout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(login_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(login_panelLayout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(loginwindow_usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(login_panelLayout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(loginwindow_passwordField)))
                .addContainerGap(111, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, login_panelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(loginwindow_loginButton, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(46, 46, 46))
        );
        login_panelLayout.setVerticalGroup(
            login_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(login_panelLayout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(login_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(loginwindow_usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(login_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(loginwindow_passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
                .addComponent(loginwindow_loginButton)
                .addGap(21, 21, 21))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(login_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(login_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginwindow_loginButtonFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_loginwindow_loginButtonFocusGained
        GuiUtil.buttonFocusGained(loginwindow_loginButton);
    }//GEN-LAST:event_loginwindow_loginButtonFocusGained

    private void loginwindow_loginButtonFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_loginwindow_loginButtonFocusLost
        GuiUtil.buttonFocusLost(loginwindow_loginButton);
    }//GEN-LAST:event_loginwindow_loginButtonFocusLost

    private void loginwindow_loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginwindow_loginButtonActionPerformed
        String username = loginwindow_usernameField.getText();
        String password = String.valueOf(loginwindow_passwordField.getPassword());
        if (username == null || username.equals("")) {
            JOptionPane.showMessageDialog(this, "Please enter valid username", "", JOptionPane.WARNING_MESSAGE);
        } else {
            if (password == null || password.equals("")) {
                JOptionPane.showMessageDialog(this, "Please enter password", "", JOptionPane.WARNING_MESSAGE);
            } else {
                try {
                    dbConnector = new MySqlConnector(DBConstant.DEFAULT_USERNAME, DBConstant.DEFAULT_PASSWORD);
                    try {
                        ResultSet res;
                        res = dbConnector.getPassword(username , role);
                        if (res != null) {
                            if(res.first()){
                                 String dbpaswd = res.getString(DBConstant.CREDENTIAL_PASSWORD);
                            if (dbpaswd.equals(password)) {
                                this.setVisible(false);
                                loginwindow_usernameField.setText("");
                                loginwindow_passwordField.setText("");
//                                pBag.addStringProperty(Constants.CURRENT_USER, username);
                                this.setVisible(false);
                                dbConnector.close();
//                                new MainWindow(pBag).setVisible(true);
                                new MainWindow(username , role).setVisible(true);
                                this.dispose();
                            } else {
                                loginwindow_passwordField.setText("");
                                JOptionPane.showMessageDialog(this, "Wrong username or password ");
                            }
                            }else{
                                                                loginwindow_passwordField.setText("");
                                JOptionPane.showMessageDialog(this, "Wrong username or password or role");
                            }
                           
                        }else {
                                loginwindow_passwordField.setText("");
                                JOptionPane.showMessageDialog(this, "Wrong username or password ");
                            }

                    } catch (SQLException ex) {
                        Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (SQLException ex) {
                    if (ex instanceof CommunicationsException) {
                        JOptionPane.showMessageDialog(null, "Server doesn't response", "Database connection error", JOptionPane.ERROR_MESSAGE);
                        loginwindow_passwordField.setText("");
                    } else {
                        Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }
        }        // TODO add your handling code here:
    }//GEN-LAST:event_loginwindow_loginButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
      new StartWindow().setVisible(true);
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginWindow().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel login_panel;
    private javax.swing.JButton loginwindow_loginButton;
    private javax.swing.JPasswordField loginwindow_passwordField;
    private javax.swing.JTextField loginwindow_usernameField;
    // End of variables declaration//GEN-END:variables

    private FocusTraversalPolicy setFocusTraversalPolicy() {
        return new FocusTraversalPolicy() {
            @Override
            public Component getComponentAfter(Container aContainer, Component aComponent) {
                if (aComponent.equals(loginwindow_usernameField)) {
                    return loginwindow_passwordField;
                } else if (aComponent.equals(loginwindow_passwordField)) {
                    return loginwindow_loginButton;
                } else if (aComponent.equals(loginwindow_loginButton)) {
                    return loginwindow_usernameField;
                }
                return aComponent;
            }

            @Override
            public Component getComponentBefore(Container aContainer, Component aComponent) {
                if (aComponent.equals(loginwindow_passwordField)) {
                    return loginwindow_usernameField;
                } else if (aComponent.equals(loginwindow_loginButton)) {
                    return loginwindow_passwordField;
                } else if (aComponent.equals(loginwindow_usernameField)) {
                    return loginwindow_loginButton;
                }
                return aComponent;
            }

            @Override
            public Component getFirstComponent(Container aContainer) {
                return loginwindow_usernameField;
            }

            @Override
            public Component getLastComponent(Container aContainer) {
                return loginwindow_loginButton;
            }

            @Override
            public Component getDefaultComponent(Container aContainer) {
                return loginwindow_usernameField;
            }
        };
    }
}
